Ruby 日記 47日目: 配列とその要素の凍結
#Ruby_日記 #2021-12-01
https://rex.libertyfish.co.jp/exam_histories/42141/user_answers/802305eb-333c-47a8-b5d4-2230b4dd0445
次のコードを実行するとどうなりますか
code:main.rb
CONST_LIST_A = '001', '002', '003'
begin
CONST_LIST_A.map{|id| id << 'hoge'}
rescue
end
CONST_LIST_B = '001', '002', '003'.freeze
begin
CONST_LIST_B.map{|id| id << 'hoge'}
rescue
end
CONST_LIST_C = '001', '002', '003'.freeze
begin
CONST_LIST_C.map!{|id| id << 'hoge'}
rescue
end
CONST_LIST_D = '001', '002', '003'.freeze
begin
CONST_LIST_D.push('add')
rescue
end
p CONST_LIST_A
p CONST_LIST_B
p CONST_LIST_C
p CONST_LIST_D
選択肢:
code:sh
"001hoge", "002hoge", "003hoge"
"001hoge", "002hoge", "003hoge"
"001", "002", "003"
"001", "002", "003", "add"
code:sh
"001hoge", "002hoge", "003hoge"
"001", "002", "003"
"001hoge", "002hoge", "003hoge"
"001", "002", "003"
code:sh
"001hoge", "002hoge", "003hoge"
"001hoge", "002hoge", "003hoge"
"001hoge", "002hoge", "003hoge"
"001", "002", "003"
code:sh
"001hoge", "002hoge", "003hoge"
"001hoge", "002hoge", "003hoge"
"001", "002", "003"
"001", "002", "003"
解説:
Arrayのfreezeに関する話だね〜
Ruby 日記 44日目: 配列とその要素の凍結
code:rb
CONST_LIST_A = '001', '002', '003'
begin
CONST_LIST_A.map{|id| id << 'hoge'}
rescue
end
各要素に hoge が追記されるね
code:rb
CONST_LIST_B = '001', '002', '003'.freeze
begin
CONST_LIST_B.map{|id| id << 'hoge'}
rescue
end
Arrayがfreezeされても、その中の要素はfreezeされないので、各要素に hoge が追記されるね
code:rb
CONST_LIST_C = '001', '002', '003'.freeze
begin
CONST_LIST_C.map!{|id| id << 'hoge'}
rescue
end
freezeされたArrayに対する破壊的な変更はエラーになるので、rescueされて ['001', '002', '003'] のまま。
instance method Array#collect! (Ruby 2.1.0)
code:rb
CONST_LIST_D = '001', '002', '003'.freeze
begin
CONST_LIST_D.push('add')
rescue
end
上と同様。freezeされたArrayに対する破壊的な変更はエラーになるので、rescueされて ['001', '002', '003'] のまま。
instance method Array#push (Ruby 2.1.0)
なので正解は4番目。
code:sh
# ruby gold/ex47/main.rb
"001hoge", "002hoge", "003hoge"
"001hoge", "002hoge", "003hoge"
"001", "002", "003"
"001", "002", "003"